package com.example.zhapp_java.adapters;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.example.zhapp_java.R;
import com.example.zhapp_java.api.ApiClient;
import com.example.zhapp_java.api.ApiService;
import com.example.zhapp_java.models.Phase;

import java.util.List;
import java.util.function.Consumer;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PhaseAdapter extends RecyclerView.Adapter<PhaseAdapter.ViewHolder> {
    private List<Phase> phases;
    private Consumer<Phase> onItemClick;
    private int selectedPosition = -1;

    public int getSelectedPosition() {
        return selectedPosition;
    }

    public Phase getSelectedPhase() {
        if (selectedPosition >= 0 && selectedPosition < phases.size()) {
            return phases.get(selectedPosition);
        }
        return null;
    }

    public PhaseAdapter(List<Phase> phases, Consumer<Phase> onItemClick) {
        this.phases = phases;
        this.onItemClick = onItemClick;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_phase, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        Phase phase = phases.get(position);
        holder.tvPhaseId.setText(phase.getPhraseId());
        holder.tvDesc.setText(phase.getPhraseDesc());

        // 高亮显示选中项
        holder.itemView.setBackgroundColor(
                position == selectedPosition ?
                        holder.itemView.getContext().getColor(R.color.purple_200) :
                        Color.TRANSPARENT
        );

        holder.itemView.setOnClickListener(v -> {
            // 更新选中位置
            int previous = selectedPosition;
            selectedPosition = position;
            if (previous != -1) notifyItemChanged(previous);
            notifyItemChanged(selectedPosition);
            onItemClick.accept(phase);
        });

        holder.btnEdit.setOnClickListener(v -> editPhase(holder.itemView.getContext(), phase));
        holder.btnDelete.setOnClickListener(v -> deletePhase(holder.itemView.getContext(), phase));
    }

    @Override
    public int getItemCount() {
        return phases.size();
    }

    public void updateList(List<Phase> newList) {
        phases = newList;
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvPhaseId, tvDesc;
        ImageButton btnEdit, btnDelete;

        ViewHolder(View itemView) {
            super(itemView);
            tvPhaseId = itemView.findViewById(R.id.tvPhaseId);
            tvDesc = itemView.findViewById(R.id.tvPhaseDesc);
            btnEdit = itemView.findViewById(R.id.btnEdit);
            btnDelete = itemView.findViewById(R.id.btnDelete);
        }
    }

    // 修改方法签名：添加 Context 参数
    private void editPhase(Context context, Phase phase) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        LayoutInflater inflater = LayoutInflater.from(context);
        View dialogView = inflater.inflate(R.layout.dialog_add_phase, null);

        EditText etBudget = dialogView.findViewById(R.id.etPhaseBudget);
        EditText etDesc = dialogView.findViewById(R.id.etPhaseDesc);

        etBudget.setText(String.valueOf(phase.getPhraseBudget()));
        etDesc.setText(phase.getPhraseDesc());

        builder.setView(dialogView)
                .setTitle("编辑阶段")
                .setPositiveButton("保存", (dialog, id) -> {
                    try {
                        phase.setPhraseBudget(Integer.parseInt(etBudget.getText().toString()));
                    } catch (NumberFormatException e) {
                        // 处理无效数字输入
                        Toast.makeText(context, "请输入有效的预算金额", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    phase.setPhraseDesc(etDesc.getText().toString());
                    updatePhase(phase);
                })
                .setNegativeButton("取消", null);

        builder.create().show();
    }

    private void updatePhase(Phase phase) {
        ApiService api = ApiClient.getClient().create(ApiService.class);
        Call<Void> call = api.updatePhase(phase.getProjectNo(), phase);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                // 错误处理
            }
        });
    }

    private void deletePhase(Context context, Phase phase) {
        new AlertDialog.Builder(context)
                .setTitle("删除阶段")
                .setMessage("确定要删除这个阶段吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    // 实际删除逻辑
                    ApiService api = ApiClient.getClient().create(ApiService.class);
                    Call<Void> call = api.deletePhase(phase.getProjectNo(), phase.getPhraseId());
                    call.enqueue(new Callback<Void>() {
                        @Override
                        public void onResponse(Call<Void> call, Response<Void> response) {
                            if (response.isSuccessful()) {
                                int position = phases.indexOf(phase);
                                phases.remove(phase);
                                notifyItemRemoved(position);
                            }
                        }

                        @Override
                        public void onFailure(Call<Void> call, Throwable t) {
                            Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                })
                .setNegativeButton("取消", null)
                .show();
    }
}